package com.joshua.spring.integration.authenticator;

import com.joshua.spring.entity.dto.UserInfoDTO;
import com.joshua.spring.entity.dto.UserQueryDTO;
import com.joshua.spring.entity.em.AuthTypeEnum;
import com.joshua.spring.entity.em.ResponseEnum;
import com.joshua.spring.integration.IntegrationAuthentication;
import com.joshua.spring.integration.exception.IntegrationAuthenticationServiceException;
import com.joshua.spring.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import static com.joshua.spring.entity.em.ResponseEnum.NULL_USERNAME_PWD;
import static com.joshua.spring.entity.em.ResponseEnum.USER_NOT_FOUND;

/**
 * com.joshua.spring.business.integration -- PasswordAuthenticator
 * description: 定义密码登录认证器
 *
 * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @date 2020/1/6 14:19
 */
@Component
public class PasswordAuthenticator implements IntegrationAuthenticator {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserInfoDTO authenticate(IntegrationAuthentication entity) {
        String username = entity.getAuthParameter("username");
        String password = entity.getAuthParameter("password");
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new IntegrationAuthenticationServiceException(NULL_USERNAME_PWD);
        }
        UserInfoDTO dto = userService.queryUser(UserQueryDTO.builder()
                .username(username).build());
        if (ObjectUtils.isEmpty(dto)) {
            throw new IntegrationAuthenticationServiceException(USER_NOT_FOUND);
        }
        if (passwordEncoder.matches(password, dto.getPassword())) {
            return dto;
        }
        return null;
    }

    @Override
    public void prepare(IntegrationAuthentication authentication) {

    }

    @Override
    public boolean support(IntegrationAuthentication entity) {
        boolean result = AuthTypeEnum.PASSWORD.equals(entity.getAuthType());
        return result;
    }

    @Override
    public void complete(IntegrationAuthentication authentication) {

    }

}
